<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyPreparatoryOverviewCHModel;
use App\Remote\Guanyuan\GuanyuanRemote;
use App\Remote\Guanyuan\GuanyuanRetry\GuanyuanRetryRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class SysGyPreparatoryOverviewCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyPreparatoryOverviewCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 筹备总览-》clickhouse ';

    protected int $id;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        try {
            $fields = [
                "month",
                "region",
                "province",
                "city",
                "cityClassification",
                "exceptionPreparation",
                "normalPreparation",
                "actualNewOpening",
                "newTarget",
                "theMonthRemainsOpen",
                "monthExceptionPreparation",
                "expectedToOpen",
                "totalNumberOfStoresPrepared",
            ];

            $last        = GyPreparatoryOverviewCHModel::query()->orderByDesc("id")->first();
            if ($last) {
                $this->id        = $last->id;
                $initExecuteDate = $executeDate = Carbon::createFromDate($last->month)
                                                        ->subDay()->startOfMonth()->format("Y-m-d");
            } else {
                $this->id        = 0;
                $initExecuteDate = $executeDate = "2023-01-01";
            }

            $todayDate   = Carbon::now()->startOfMonth()->format("Y-m-d");
            $batchInsert = [];
            while ($executeDate <= $todayDate) {
                $this->getOutput()
                     ->info("$executeDate 正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]");
                $data = GuanyuanRetryRemote::sourceData(
                    'r4b3354876071452faaec289',
                    'g15f9d0fbed824867b8334d0',
                    [
                        [
                            'name'        => '月份',
                            'filterType'  => 'EQ',
                            'filterValue' => [$executeDate]
                        ]
                    ]
                );


                if (empty($data["data"]) && $todayDate != $executeDate) {
                    //执行脚本日期 == 拉取观远数据日期 数据为空此时为异常状态
                    throw new \Exception("观远拉取数据异常 [ $executeDate ]");
                }

                $this->getOutput()->info("当月数据量 :  " . count($data["data"] ?? []));
                collect($data["data"])->each(function ($row) use (
                    $fields,
                    &$batchInsert,
                    $executeDate
                ) {
                    collect($row)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                        if (isset($fields[$key])) {
                            $insert[$fields[$key]] = $value;
                        } else {
                            return false;
                        }
                    });

                    $this->id = $this->id + 1;
                    array_push($batchInsert, array_merge(
                            $insert, [
                            "createdAt" => time(),
                            "id"        => $this->id,
                            "updatedAt" => 0
                        ])
                    );
                });

                $executeDate = Carbon::createFromTimestamp(strtotime($executeDate))
                                     ->addMonth()->firstOfMonth()->format("Y-m-d");
            }

            if ($batchInsert) {
                GyPreparatoryOverviewCHModel::query()->where("month", ">=", $initExecuteDate)->delete();
                collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                    GyPreparatoryOverviewCHModel::query()->insert($collection->values()->toArray());
                });
            }

            logInfo("{$this->description} 成功", collect([]), true, false);
        } catch (\Exception $exception) {
            logException("{$this->description} 失败 : {$exception->getMessage()}", $exception, null, true, true);
        }
        return 0;
    }
}
